/*
    博文模块相关api
*/
var express = require("express");
var router = express.Router();
var fs = require("fs");
var path = require("path");
const parseUrl = require('url');
var queryString = require("querystring")

//const curUrl = 'http://192.168.1.107:3000' //测试环境地址
const curUrl = 'http://118.178.182.26:3000' //正式环境地址

const multer = require('multer');//图片上传中间件
var upload = multer({ dest: path.resolve('./public/uploads/') }) //上传图片储存路径
var type = upload.single('image')

const blog = require("../controller/blog.js")

const { sqlQuery } = require('../mysql/index')

// 获取所有博文列表
router.get('/getBlogList', (req, res) => {
    let page = req.query.page;
    blog.getBlogList(page).then(data => {
        res.send(JSON.stringify(data))
    }).catch((err) => {
        res.send(err)
    })
})

// 根据ID获取博文信息
router.get('/getBlogById', (req, res) => {
    let uid = req.query.id
    blog.visitBlog(uid).then(result => {
        blog.getBlogById(uid).then(data => {
            res.send(JSON.stringify(data))
        })
    })

})

//新添博文
router.post('/addBlog', (req, res) => {
    const data = req.body;
    blog.addBlog(data).then(result => {
        res.send(JSON.stringify(result))
    })
})

//图片上传
router.post('/uploader', type, (req, res) => {
    let file = req.file;
    console.log(file)
    res.send({ url: `${curUrl}/uploads/` + file.filename })
});

//上传图片删除
router.get('/deleteImg', (req, res) => {
    let url = ('public/' + req.query.url.split('/')[3] + '/').concat(req.query.url.split('/')[4])
    fs.unlink(url, () => {
        res.send({ msg: 'ok' })
    });
});

//标题关键词搜索
router.post('/search', (req, res) => {
    let msg = req.body.msg
    blog.getBlogList(-1).then(data => {
        blog.searchBlog(msg, data).then(result => {
            res.send(result)
        });
    })
});


module.exports = router
